package com.anxuan.wiki.service;


import com.anxuan.wiki.domain.Category;
import com.anxuan.wiki.domain.CategoryExample;
import com.anxuan.wiki.mapper.CategoryMapper;
import com.anxuan.wiki.req.CategoryQueryReq;
import com.anxuan.wiki.req.CategorySaveReq;
import com.anxuan.wiki.resp.CategoryQueryResp;
import com.anxuan.wiki.resp.PageResp;
import com.anxuan.wiki.util.CopyUtil;
import com.anxuan.wiki.util.SnowFlake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class CategoryService {
    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private SnowFlake snowFlake;

    public PageResp<CategoryQueryResp> list(CategoryQueryReq req){
        PageHelper.startPage(req.getPage(), req.getSize());
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.setOrderByClause("sort asc");
        CategoryExample.Criteria criteria = categoryExample.createCriteria();
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);
        PageInfo<Category> pageInfo = new PageInfo<>(categoryList);
        log.info("总行数:{}",pageInfo.getTotal());
        log.info("总页数:{}",pageInfo.getPages());


        /*
        持久层返回List<Category>
        需要转换成 List<CategoryResp>
        再返回controller
         */
        List<CategoryQueryResp> respList = new ArrayList<>();
       /* for (Category category:categoryList) {
         对象复制   CategoryResp categoryResp = CopyUtil.copy(category, CategoryResp.class);
            respList.add(categoryResp);

        }*/

        List<CategoryQueryResp> list = CopyUtil.copyList(categoryList, CategoryQueryResp.class);
        PageResp<CategoryQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;


    }


    public List<CategoryQueryResp> all(){

        CategoryExample categoryExample = new CategoryExample();
        categoryExample.setOrderByClause("sort asc");
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);
        List<CategoryQueryResp> list = CopyUtil.copyList(categoryList, CategoryQueryResp.class);
        return list;


    }
    //保存
    public void save(CategorySaveReq req){
        Category category = CopyUtil.copy(req,Category.class);
        if(ObjectUtils.isEmpty(req.getId())){
            //新增
            category.setId(snowFlake.nextId());
            categoryMapper.insert(category);
        }else{
            //更新
            categoryMapper.updateByPrimaryKey(category);
        }


    }


    public void delete(Long id){
        categoryMapper.deleteByPrimaryKey(id);
    }

}
